// Copyright 2019 The rhyme_lph Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// F [author] rhyme_lph
// v [email]  rhymelph@gmail.com
// n [github] https://github.com/rhymelph

import 'dart:async';

import 'package:base_plugin/base_plugin.dart';
import 'package:dio/src/response.dart';
import 'package:finance_app/src/common/config.dart';
import 'package:finance_app/src/entities/quotation_entity.dart';
import 'package:finance_app/src/http_service/http_quotation_service.dart';
import 'package:finance_app/src/mixin/check_plan_mixin.dart';
import 'package:finance_app/src/mixin/format_group_map_mixin.dart';
import 'package:finance_app/src/mixin/refresh_mixin.dart';
import 'package:finance_app/src/mixin/search_data_list_mixin.dart';
import 'package:finance_app/src/router_gen/router_gen_providers.dart';
import 'package:finance_app/src/widgets/bottom_sheet/delete_info_bottom_sheet.dart';
import 'package:flutter/material.dart';
import 'package:finance_app/src/page/dashboard/quotation/quotation_number_page.dart';

class QuotationNumberProvider extends BaseProvider<List<QuotationEntity>>
    with
        SearchDataListMixin<List<QuotationEntity>>,
        FormatGroupMapLocalMixin<QuotationEntity>,
        RefreshMixin<List<QuotationEntity>, List<QuotationEntity>>,
        CheckPlanMixin {
  QuotationEntity currentSelect;

  int contactId;

  String keyword;

  @override
  Future get dataFuture => HttpQuotationService.quotationsList(page,
      status: "open", issue_to: contactId, keyword: keyword);

  void onSelect(QuotationEntity item1) {
    if (currentSelect?.id == item1?.id) return;
    currentSelect = item1;
    update();
    obtainContext?.call((context) {
      Navigator.of(context).pop(currentSelect);
    });
  }

  //添加quotation
  void onNavAddQuotation() async {
    if (isPlanExpired()) return;
    final result =
        await Routes.navigateTo(RouterGenProviders.newQuotationPage, params: {
      'isSelectMode': true,
    });
    if (result != null) {
      data.add(result);
      onSelect(result);
    }
  }

  @override
  void searchRefreshData(searchData) async {
    keyword = searchData;
    page = 1;
    await post(refreshFuture, autoHandler: AutoHandler.Toast,
        onSuccess: (result) {
      data = getFromRequestResult(result, true);
      update();
    }, onFinally: () {
      if (data == null) {
        data = [];
      }
      update();
    });
  }

  @override
  FutureOr<List<QuotationEntity>> transformData(
      List<QuotationEntity> d, bool isCache) {
    return super.transformData(d, isCache);
  }

  @override
  List<QuotationEntity> get dataList => data;

  @override
  List<QuotationEntity> getFromRequestResult(Response result, bool isRefresh) {
    return getEntityFromResult(result);
  }

  @override
  Future get refreshFuture => dataFuture;
}
